<?php

namespace app\api\logic;

use think\facade\Db;
use app\data\util\HttpUtil;
use think\exception\ValidateException;
use think\facade\Cache;
use app\api\logic\FeiShuTalkLogic;
use app\api\logic\FeiShuMessageLogic;
use think\cache\driver\Redis;

class ApiGiftCardLogic extends BasicLogic
{
    public function __construct()
    {

    }

    /**
    * @desc    GiftCardlist
    * @date    2025/01/01
    * @author  zhangheng
    */
    public function GiftCardlist($params=[])
    {
        $shop_id        = $params['shop_id'] ?? 0;
        if(empty($shop_id)){
            return  $this->jsonMessage(201,false,'店铺ID不能为空','');
        }
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $gift_cards     = Config('Logisticskey.shopify.gift_cards');
        $url            = $shop_info['myshopify_domain'].$version . $gift_cards;
        $url = $url . '?limit=250&status=enabled';
        //拉取历史
        $desc = $params['desc'] ?? 'desc';
        $order = $desc == 'desc' ? "created_at desc" : "created_at asc";
        $giftcard = Db::name('gift_card')->where('type','API')->order($order)->find();
        if (!empty($giftcard)) {
            $url = $url . '&since_id='.$giftcard['card_id'];
        }
        $return = HttpUtil::getUrl($url, $shop_info);
        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors'])."店铺名称：".$shop_info['name'], null));
        }
        $gift_cards = $return['gift_cards'] ?? [];
        if (is_array($gift_cards) && !empty($gift_cards)) {
            foreach ($gift_cards as $card) {
                $insert = [
                    'shop_id' => $shop_id,
                    'card_id' => $card['id'] ?? "",
                    'balance' => $card['balance'] ?? "", 
                    'currency' => $card['currency'] ?? "",
                    'initial_value' => $card['initial_value'] ?? "",
                    'line_item_id' => $card['line_item_id'] ?? "",
                    'api_client_id' => $card['api_client_id'] ?? "",
                    'user_id' => $card['user_id'] ?? "",
                    'customer_id' => $card['customer_id'] ?? "",
                    'note' => $card['note'] ?? "",
                    'expires_on' => $card['expires_on'] ?? "",
                    'template_suffix' => $card['template_suffix'] ?? "",
                    'last_characters' => $card['last_characters'] ?? "",
                    'order_id' => $card['order_id'] ?? "",
                    'created_at' => $card['created_at'] ?? "",
                    'updated_at' => $card['updated_at'] ?? "",
                    'disabled_at' => $card['disabled_at'] ?? "",
                ];
                $order_dispute_api = Db::name('gift_card')->where(['card_id' => $insert['card_id']])->find();
                if ($order_dispute_api) {
                    Db::name('gift_card')->where(['card_id' => $insert['card_id']])->update($insert);
                } else {
                    $insert['type'] = 'API';
                    Db::name('gift_card')->insert($insert);
                }
            }
            return  $this->jsonMessage(200,true,'操作成功','');
        }else{
            return  $this->jsonMessage(201,false,'暂无数据','');
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    /**
    * @desc    GiftCardfind
    * @date    2025/01/01
    * @author  zhangheng
    */
    public function GiftCardfind($params=[])
    {
        $shop_id        = $params['shop_id'] ?? 0;
        if(empty($shop_id)){
            return  $this->jsonMessage(201,false,'店铺ID不能为空','');
        }
        $card_id        = $params['card_id'] ?? 0;
        if(empty($card_id)){
            return  $this->jsonMessage(201,false,'礼品卡ID不能为空','');
        }
        $shop_info  = Db::name('shops')->where('id',$shop_id)->find();
        $version    = Config('Logisticskey.shopify.api_versoin');
        $url        = $shop_info['myshopify_domain'].$version . '/gift_cards/'.$card_id.'.json';
        $return = HttpUtil::getUrl($url, $shop_info);
        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors'])."店铺名称：".$shop_info['name'], null));
        }
        halt($return);
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    /**
    * @desc    GiftCardadd
    * @date    2025/01/01
    * @author  zhangheng
    */
    public function GiftCardadd($params=[])
    {
        $gift_card = Db::name('gift_card')
            ->where('type','手动录入')
            ->where('status',0)
            ->limit(10)
            ->select()->toarray();
        foreach ($gift_card as $k=>$v) {
            $this->GiftCardadds($v);
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }
    /**
    * @desc    GiftCardadd
    * @date    2025/01/01
    * @author  zhangheng
    */
    public function GiftCardadds($params=[])
    {
        $shop_id        = $params['shop_id'] ?? 0;
        if(empty($shop_id)){
            return false;
        }
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $gift_cards     = Config('Logisticskey.shopify.gift_cards');
        $url            = $shop_info['myshopify_domain'].$version . $gift_cards;

        //api传参
        $data = [];
        $data['note'] = "This is a note";
        $data['initial_value'] = $params['initial_value'] ?? 0;
        $data['code'] = $params['code'] ?? "";
        $data['template_suffix'] = "gift_cards.birthday.liquid";
        $datas['gift_card'] = $data;

        $return = HttpUtil::PostUrl($url,$datas, $shop_info);
        $return = json_decode($return, true);
        if (!empty($return['errors'])) {
            //日志记录
            $update = [
                'msg' => json_encode($return['errors'])."店铺名称：".$shop_info['name'],
                'status' => 2,
            ];
            Db::name('gift_card')->where(['id' => $params['id']])->update($update);

            // 飞书消息---个人消息
            $FeiShuMessageLogic = new FeiShuMessageLogic();
            $system_admin = Db::name('system_admin')->field('open_id')->where('id',2)->find();
            $open_id = $system_admin['open_id'] ?? 0;
            if($open_id){
                $datamsg = [
                    'message' => "生成代金券错误：".$update['msg'],
                    'open_id' => $open_id,
                ];
                $FeiShuMessageLogic->send_message($datamsg);
            }

            return true;
        }else{
            $update = [
                'msg' => "生成代金券成功",
                'status' => 1,
            ];
            Db::name('gift_card')->where(['id' => $params['id']])->update($update);

            // 飞书消息---个人消息
            // $FeiShuMessageLogic = new FeiShuMessageLogic();
            // $system_admin = Db::name('system_admin')->field('open_id')->where('id',2)->find();
            // $open_id = $system_admin['open_id'] ?? 0;
            // if($open_id){
            //     $datamsg = [
            //         'message' => $update['msg'],
            //         'open_id' => $open_id,
            //     ];
            //     $FeiShuMessageLogic->send_message($datamsg);
            // }

            return true;
        }
        
    }
}
